package com.yanxibao.util;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yanxibao.dto.PageQueryDTO;
import org.springframework.lang.Nullable;

import java.util.Map;

/**
 * 分页查询工具类
 *
 * @author kongke
 * @date 2023/11/15
 */
public class QueryUtil {

    /**
     * 筛选查询
     * <p>
     * ge、gt、le、lt、
     * 大于等于、大于、小于等于、小于
     *
     * @param entity   实体类
     * @param mapper   实体类对应mapper
     * @param Qwrapper queryWrapper
     * @param page     分页参数
     */
    public static <T> Object FltQuery(String fltType, T entity, @Nullable Page<T> page,
                                      BaseMapper<T> mapper, @Nullable QueryWrapper<T> Qwrapper) {

        QueryWrapper<T> wrapper = null;

        wrapper = Qwrapper != null ? Qwrapper : new QueryWrapper<>();

//       添加查询条件
        if (BeanUtil.isNotEmpty(entity)) {

            Map<String, Object> map = BeanUtil.beanToMap(entity, true, true);

            switch (fltType) {
                case "eq" -> map.forEach(wrapper::eq);
                case "ge" -> map.forEach(wrapper::ge);
                case "le" -> map.forEach(wrapper::le);
                default -> {}
            }

        }

//      page非空则分页
        return isPage(page, mapper, wrapper);

    }

    /**
     * 判断是否分页
     */
    private static <T> Object isPage(Page<T> page, BaseMapper<T> mapper, QueryWrapper<T> wrapper) {
        if (page != null) {
            PageQueryDTO<T> dto = new PageQueryDTO<>();
            Page<T> selectPage = mapper.selectPage(page, wrapper);

            dto.setList(selectPage.getRecords());
            dto.setCount(selectPage.getTotal());
            return dto;
        } else {

            return mapper.selectList(wrapper);
        }
    }


}
